package com.sunday.fangdaifu.widgets;

/**
 * 2017/6/30 16:06
 * Created by FREECSDN on 2017/6/30.
 */

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.sunday.common.utils.PixUtils;
import com.sunday.fangdaifu.R;

import java.util.HashMap;

/**
 * Created by Administrator on 2015/7/23.
 */
public class SectorMenu extends View {
    private Context mContext;

    private HashMap<String, MenuItem> mMenuItems = new HashMap<String, MenuItem>();


    /**
     * 盘块的个数
     */
    private int mItemCount = 0;

    /**
     * 绘制盘块的范围
     */
    private RectF mRange = new RectF();

    /**
     * 中心圆的位置
     */

    private RectF centerRange ;

    /**
     * 圆的直径
     */
    private int mRadius;
    /**
     * 绘制盘快的画笔
     */
    private Paint mArcPaint;

    /**
     * 绘制文字的画笔
     */
    private Paint mTextPaint;

    private volatile float mStartAngle = 180;

    /**
     * 扇形所占的全部角度
     */

    private int mMenuRadius;

    /**
     * 控件的中心位置
     */
    private int mCenter;

    private String mPressedMenuItemID;

    private boolean isMenuItemPressed;//menu是否被选中

    private boolean isMenuTogglePressed;//中心菜单是否被选中

    private OnMenuSelectListener onMenuSelectListener;

    /**
     * 文字的大小
     */
    private float mTextSize;


    private Path mPath;

    public SectorMenu(Context context) {
        this(context,null);
    }

    public SectorMenu(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SectorMenu(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;

        // setZOrderOnTop(true);// 设置画布 背景透明
        // mHolder.setFormat(PixelFormat.TRANSLUCENT);
        setFocusable(true);
        setFocusableInTouchMode(true);
        ///  this.setKeepScreenOn(true);

    }


    private void inite(){
        // 初始化绘制圆弧的画笔
        mArcPaint = new Paint();
        mArcPaint.setAntiAlias(true);
        mArcPaint.setDither(true);
        // 初始化绘制文字的画笔
        mTextPaint = new Paint();
        mTextPaint.setColor(0xFFffffff);
        mTextSize = PixUtils.sp2px(mContext,20);
        mTextPaint.setTextSize(mTextSize);
        this.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        // 圆弧的绘制范围
        mRange = new RectF(getPaddingLeft(), getPaddingLeft(), mRadius
                + getPaddingLeft(), mRadius + getPaddingLeft());
        int mItem = PixUtils.dip2px(mContext,60);
        centerRange = new RectF(mCenter-mItem, mCenter-mItem, mCenter+mItem,mCenter+mItem);
    }
    /**
     * 设置控件为正方形
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = Math.min(getMeasuredWidth(), getMeasuredHeight());
        // 获取圆形的直径
        mRadius = width - getPaddingLeft() - getPaddingRight();
        // 中心点
        mCenter = width / 2;
        setMeasuredDimension(width, width);
        inite();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawBg(canvas);

        /**
         * 绘制每个块块，每个块块上的文本，每个块块上的图片
         */
        float tmpAngle = 22.5f;
        float sweepAngle = (float) 45;
        int i = 0;
        for (MenuItem item : mMenuItems.values()) {
            mArcPaint.setColor(item.getBackgroundColor());
            this.mPath = item.getMenuPath();
            if(i%2==0){
                this.mArcPaint.setColor(Color.parseColor("#ffffff"));
            }else{
                this.mArcPaint.setColor(Color.parseColor("#f7f7f7"));
            }
            canvas.drawArc(mRange,tmpAngle,sweepAngle,true,mArcPaint);//画扇形

            //    mPath.arcTo(mRange, tmpAngle, sweepAngle);
            //小圆的角度
         //   mPath.arcTo(centerRange, tmpAngle + sweepAngle, -sweepAngle);
           // mPath.addRoundRect(mRange,);
            mPath.close();
            item.setMenuPath(mPath);
            canvas.drawPath(item.getMenuPath(), mArcPaint);
            drawText(canvas, tmpAngle, sweepAngle, item.getText());
            tmpAngle += sweepAngle;
            i++;
        }

        // 画原点点
        drawClockPoint(canvas);
        mArcPaint.setStyle(Paint.Style.FILL);
    }

        private void drawClockPoint(Canvas canvas) {
            Paint paint = new Paint();
            paint.setColor(Color.WHITE);
            paint.setStrokeWidth(10f);
            int radius = getWidth()/2-20;//小圆距离圆心的距离
            //画出圆上面刻度值
            for (float degree = 0; degree <= 360;degree = degree + 15) {
                //数学公式 找圆上面的点坐标
                float rad = (float )Math.toRadians(degree);//转换为度
                float x = (float) (radius * Math.sin(rad));
                float y = (float) (radius * Math.cos(rad));

              //  RectF rectF =new RectF(x + mCenter,mCenter - y,getWidth()-x-mCenter,getWidth()+y-mCenter);
             //   canvas.drawOval(rectF,paint);

                canvas.drawPoint(x + mCenter, mCenter - y,paint);
            }
        }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (centerRange.contains(x, y)) {
                    isMenuTogglePressed = true;
                    invalidate();
                } else {
                    if (mMenuItems.size() > 0) {
                        for (MenuItem item : mMenuItems.values()) {
                            if (mRange.contains((int) x, (int) y))
                                if (item.getBounds().contains((int) x, (int) y)) {
                                    isMenuItemPressed = true;
                                    mPressedMenuItemID = item.getMenuID();
                                    break;
                                }
                        }
                        if(!TextUtils.isEmpty(mPressedMenuItemID)){
                            mMenuItems.
                                    get(mPressedMenuItemID)
                                    .setBackgroundColor(mMenuItems.get(mPressedMenuItemID).getMenuSelectedColor());
                        }
                        invalidate();
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                if (isMenuTogglePressed) {
                    if(onMenuSelectListener!=null){
                        onMenuSelectListener.onSelect(null,"item");
                    }
                    isMenuTogglePressed = false;
                    invalidate();
                }
                if (isMenuItemPressed) {
                    MenuItem item = mMenuItems.get(mPressedMenuItemID);
                    if(onMenuSelectListener!=null){
                        onMenuSelectListener.onSelect(item,mPressedMenuItemID);
                    }
                    item.setBackgroundColor(mMenuItems.get(mPressedMenuItemID).getMenuNormalColor());
                    isMenuItemPressed = false;
                    invalidate();
                }
                break;
        }

        return true;
    }

    /**
     * 根据当前旋转的mStartAngle计算当前滚动到的区域 绘制背景，不重要，完全为了美观
     */
    private void drawBg(Canvas canvas) {
        canvas.drawColor(Color.TRANSPARENT);
    }



    /**
     * 绘制文本
     *
     * @param startAngle
     * @param sweepAngle
     * @param string
     */
    private void drawText(Canvas canvas, float startAngle, float sweepAngle, String string)
    {
        Path path = new Path();
        path.addArc(mRange, startAngle, sweepAngle);
        float textWidth = mTextPaint.measureText(string);
        mTextPaint.setStrokeWidth(8);
        mTextPaint.setColor(ContextCompat.getColor(mContext, R.color._808080));
        mTextPaint.setTypeface(Typeface.DEFAULT);
        //float blankWidth = mTextPaint.measureText("    ");
        // textWidth = textWidth + blankWidth;
        // 利用水平偏移让文字居中
        // float hOffset =  (float)Math.sin(sweepAngle/180)*mRadius/2-textWidth/2;
        float hOffset = (float) (mRadius * Math.PI *mMenuRadius/360/ mItemCount / 2 - textWidth / 2);// 水平偏移
        float vOffset = mRadius / 2 / 2;// 垂直偏移
        canvas.drawTextOnPath(string, path, hOffset, vOffset, mTextPaint);
    }

    public void addMenuItem(String idTag, MenuItem mMenuItem) {
        mMenuItems.put(idTag, mMenuItem);
        mMenuRadius = 360;
        mItemCount = mMenuItems.size();
        invalidate();
    }

    public void clear(){
        mItemCount = 0;
        mMenuItems.clear();
        mMenuRadius = 0;
    }

    public void setOnMenuSelectListener(OnMenuSelectListener onMenuSelectListener) {
        this.onMenuSelectListener = onMenuSelectListener;
    }

    public interface OnMenuSelectListener{
        void onSelect(MenuItem menuItem, String item);
    }

}

